package cn.santi.controller;

import cn.santi.domain.JUser;
import cn.santi.emuns.R;
import cn.santi.excel.ExcelExportUtil;
import cn.santi.service.JUserService;
import cn.santi.service.OpenidCodeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/User")
public class UserController {//用户

    @Autowired
    private JUserService jUserService;
    @Autowired
    private OpenidCodeService openidCodeService;

    @GetMapping("/openid")
    public R getOpenidByCode(String code) {//用户登录通过code获取openid
        // 假设这是你的获取openid的服务类
//        System.out.println("code::" + code);
        String appId = "wx6842a943b0ee64d3";
        String secret = "d6ba5cf2734aee17424f517b81eb75bb";
        String openid = openidCodeService.getOpenId(appId, secret, code);
        System.out.println("openid::" + openid);
        LambdaQueryWrapper<JUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JUser::getOpenid, openid);
        JUser one = jUserService.getOne(wrapper);
        if (one != null) {
//            String token= JWTs.encryption(one.getUid()+"");
            return R.ok(one, "已有数据");
        } else {
            JUser user = new JUser();
            user.setOpenid(openid);
            jUserService.save(user);
            JUser one1 = jUserService.getOne(wrapper);
//            String token = JWTs.encryption(one1.getUid()+"");
            return R.ok(one1, "刚添加");
        }
    }

    @GetMapping("/UserById")
    public R UserById(Integer uid) {//根据uid查询用户信息
        JUser byId = jUserService.getById(uid);
//        System.out.println("UserById:"+byId);
        return R.ok(byId);
    }

    @GetMapping("/updateUserById")
    public R updateUserById(JUser user) {//根据uid修改用户信息
//        System.out.println("updateUserById::"+user);
        boolean b = jUserService.updateById(user);
        if (b) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    @GetMapping("/usergetid")
//    @Cacheable(value = "myCache", key = "#id")
    public void usergetid(HttpServletResponse response, int id) throws IOException {
        System.out.println("usergetid:" + id);
//        QueryWrapper<JUser> wrapper = new QueryWrapper<>();
//        wrapper.eq("uid",id);
        List<JUser> one = jUserService.list();
//        System.out.println(one);
        ExcelExportUtil.exportExcel(response, one);
//        return R.ok(one);
    }

    @GetMapping("/getUserCoent")
    public R getUserCoent() {//获取用户数量
        List<JUser> one = jUserService.list();
        return R.ok(one.size());
    }

}
